import { CSSProperties, computed, ref } from 'vue';
import { CloudUploadOutlined } from '@ant-design/icons-vue';
import { useElementSize } from '@vueuse/core';
import {
  Button,
  Flex,
  Modal,
  Space,
  Upload,
  UploadProps,
  message,
} from 'ant-design-vue';
import { VueCropper } from 'vue-cropper';
import 'vue-cropper/dist/index.css';

interface Config {
  /** 图片宽度 */
  width: number;
  /** 图片高度 */
  height: number;
  request: (file: Blob) => Promise<void>;
}

interface Opt {
  title?: string;
  img?: string;
}

export const useCropper = (config: Config) => {
  const cropperRef = ref();
  const cutBoxRef = ref();
  const visible = ref(false);

  const title = ref('');
  const img = ref('');

  const customRequest: UploadProps['customRequest'] = ({ file, onSuccess }) => {
    onSuccess(null);
    if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(file.name)) {
      message.info('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种');
      return false;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      console.log(e);

      let data;
      if (typeof e.target.result === 'object') {
        // 把Array Buffer转化为blob 如果是base64不需要
        data = window.URL.createObjectURL(new Blob([e.target.result]));
      } else {
        data = e.target.result;
      }
      img.value = data;
    };
    // 转化为base64
    // reader.readAsDataURL(file)
    // 转化为blob
    reader.readAsArrayBuffer(file);
  };

  const preview = ref<{
    url: string;
    img: CSSProperties;
    div: CSSProperties;
    w: number;
    h: number;
  }>({
    url: '',
    div: {},
    img: {},
    h: 0,
    w: 0,
  });
  const onRealTime = (data) => {
    preview.value = data;
  };

  const open = (opt: Opt) => {
    title.value = opt.title;
    img.value = opt.img || '';
    visible.value = true;
  };

  const onDown = () => {
    return new Promise<void>((resolve, reject) => {
      try {
        cropperRef.value.getCropBlob(async (data) => {
          await config.request(data);
          visible.value = false;
          resolve();
        });
      } catch (error) {
        reject(error);
      }
    });
  };

  const CropperModal = () => {
    return (
      <Modal
        title={title.value}
        v-model:open={visible.value}
        maskClosable
        destroyOnClose
        width={700}
        onOk={() => onDown()}
      >
        <Flex justify='space-between'>
          <div
            class='cut'
            ref={cutBoxRef}
            style={{
              flex: '1',
              overflow: 'hidden',
              height: '500px',
              marginBottom: '50px',
            }}
          >
            <VueCropper
              ref={cropperRef}
              img={img.value}
              autoCrop
              onRealTime={onRealTime}
              fixed
              outputType='png'
              fixedNumber={[config.width, config.height]}
              centerBox
              mode='contain'
            />
          </div>
          {/* <div style={{ flex: 1, overflow: 'hidden' }}>
            <div
              style={{
                width: `${preview.value.w}px`,
                height: `${preview.value.h}px`,
                overflow: 'hidden',
              }}
            >
              <div style={preview.value.div}>
                <img src={preview.value.url} style={preview.value.img} />
              </div>
            </div>
          </div> */}
        </Flex>
        <Space>
          <Upload customRequest={customRequest} showUploadList={false}>
            <Button>
              <CloudUploadOutlined />
              <span>上传</span>
            </Button>
          </Upload>
        </Space>
      </Modal>
    );
  };

  return {
    CropperModal,
    open,
  };
};
